import { createStore } from 'vuex'
import config from '@/config'

const store = createStore({
  state: {
    token: uni.getStorageSync('token'),
    user: uni.getStorageSync(config.userKey),

    // 是否在登录页面
    showLogin: false,
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      uni.setStorageSync('token', token)
    },

    SET_USER(state, user) {
      state.user = user
      uni.setStorageSync(config.userKey, user)
    },

    SHOW_LOGIN(state, showLogin) {
      state.showLogin = showLogin
    },

    LOGOUT(state) {
      state.user = null
      state.token = null
      uni.clearStorageSync()
    },
  },
  actions: {
    // 显示登录窗口
    showLogin({ commit, state, dispatch }) {
      commit('SHOW_LOGIN', true)
    },

    // 跳转登录页面
    goLogin({ commit, state, dispatch }) {
      // 防止多次打开
      if (state.showLogin) return
      commit('SHOW_LOGIN', true)

      // 有问题误用
      // dispatch('setLastPage');

      let url = ''

      // #ifdef H5
      url = location.pathname == '/' ? '/pages/index/index' : location.pathname.replace(config.root, '') + location.search
      // #endif

      uni.navigateTo({
        // url: `${config.loginPage}?backUrl=` + encodeURIComponent(url),
        url: `${config.loginPage}`,
      })
    },

    // 有问题误用，获取登录跳转前的URL
    setLastPage({ commit }) {
      // #ifdef H5
      const url = location.pathname == '/' ? '/pages/index/index' : location.pathname
      commit('SET_LAST_PAGE_URL', url + location.search)
      // #endif

      // #ifdef MP-WEIXIN
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      const { route, options } = page

      var url = '/' + route
      var params = ''

      if (Object.keys(options).length) {
        Object.keys(options).forEach((v) => {
          params += '&' + v + '=' + options[v]
        })
        params = params.substring(1)
      }

      if (params != '') url += '?' + params

      commit('SET_LAST_PAGE_URL', url)
      // #endif
    },

    /**
     * 验证用户是否登录或过期
     */
    checkLogin({ commit, dispatch }, needLogin = true) {
      try {
        const user = uni.getStorageSync(config.userKey)
        commit('SET_USER', user)

        // 用户未登录跳转登录界面
        if (!user && needLogin) {
          dispatch('goLogin')
          // dispatch('showLogin');
          uni.removeStorageSync(config.userKey)
          return false
        } else {
          return true
        }
      } catch (e) {
        console.error(new Error(e))
        uni.removeStorageSync(config.userKey)
      }
    },

    /**
     * 弹出消息
     */
    message({ commit }, options) {
      if (typeof options == 'string') {
        options = {
          message: options,
        }
      }

      options = {
        duration: 2000,
        ...options,
      }
      uni.showToast({
        title: options.message,
        duration: options.duration,
        mask: true,
        icon: 'none',
      })
    },

    // 注销
    logout({ commit, dispatch }) {
      commit('LOGOUT')
      dispatch('goLogin')
      // uni.reLaunch({
      //     // url: `${config.loginPage}?backUrl=/pages/index/index`,
      //     url: `${config.loginPage}`,
      // });
    },

    // 登录完成
    loginSuccess({ commit }, { token, user, goUrl }) {
      if (token) commit('SET_TOKEN', token)
      if (user) commit('SET_USER', user)

      commit('SHOW_LOGIN', false)

      // if (goUrl) {
      //     uni.reLaunch({
      //         url: decodeURIComponent(goUrl),
      //     });
      // }

      if (goUrl) {
        uni.reLaunch({
          url: decodeURIComponent(goUrl),
        })
      } else {
        uni.navigateBack()
      }
    },
  },
  modules: {
    // tabBar,
  },
})

export default store
